package online.longzipeng.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import online.longzipeng.commen.dynamic.datasource.annotation.DataSource;
import online.longzipeng.entity.User;
import online.longzipeng.mapper.UserMapper;
import online.longzipeng.service.UserService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: lzp
 * @description:
 * @Date: 2022/12/6
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Override
	public void testTransaction() throws Exception {
		UserServiceImpl userService = (UserServiceImpl) AopContext.currentProxy();
		userService.test2();
	}

	@Transactional(rollbackFor = Exception.class)
	public void test2() throws Exception {
		User user = new User();
		user.setId(1);
		user.setAge(80);
		baseMapper.updateById(user);
		int a = 5 / 0;
	}

	/**
	 * 事务中进行数据源切换，导致数据源切换失效
	 */
	@Transactional
//	@DataSource("lzp3")
	@DS("lzp3")
	@Override
	public void testDynamicDatasource() {
		User user = baseMapper.getUser();
		System.out.println(user.getNickName());

		UserServiceImpl userService = (UserServiceImpl) AopContext.currentProxy();
		userService.test3();
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
//	@DataSource("lzp2")
	@DS("lzp2")
	public void test3() {
		User user = baseMapper.getUser();
		System.out.println(user.getNickName());
	}

}
